// pages/login/login.ts
import AuthApi from "../../api/Auth"
import Toast from "tdesign-miniprogram/toast/index"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userId: "",
    password: ""
  },
  handleConfirm() {
    let userId = this.data.userId
    let password = this.data.password
    if (!userId) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: "请输入工号",
      })
      return
    }
    if (!password) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: "请输入登录密码",
      })
      return
    }
    AuthApi.login({ userId, password }).then((res: any) => {
      let token = res.data[0].token
      let user = res.data[0].user
      wx.setStorageSync("token", token)
      wx.setStorageSync("user", user)
      Toast({
        context: this,
        selector: '#t-toast',
        message: '登陆成功',
        theme: 'success',
        direction: 'column',
      })
      setTimeout(() => {
        wx.reLaunch({
          url: "/pages/index/index"
        })
      }, 300)
    }).catch(e => {
      Toast({
        context: this,
        selector: '#t-toast',
        message: e,
      })
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let userInfo = wx.getStorageSync("user")
    if (userInfo) {
      wx.reLaunch({
        url: '/pages/index/index',
      })
    }
  },
})
